package restlet;

import java.util.Iterator;
import java.util.List;
import javax.xml.xpath.XPathConstants;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Status;
import org.restlet.resource.ServerResource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class ResourceItems extends ServerResource {

	private DataItem _item;

	public ResourceItems(Context context, Request request, Response response) {
		super(context, request, response);

		// This representation has only one type of representation.
		getVariants().add(new Variant(MediaType.TEXT_XML));
	}

	@Override
	public boolean allowPut() {
		return true;
	}

	@Override
	public void put(Representation entity) {
		String name = null;
		int price = -1;
		SaxRepresentation sax = getRequest().getEntityAsSax();
		try {
			name = (String) sax.evaluate("/param/name", XPathConstants.STRING);
			price = Integer.parseInt((String) sax.evaluate("/param/price", XPathConstants.STRING));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		if (name != null && price != -1) {
			_item = new DataItem(name, price);
			if (DefaultDatabase.getItemList().add(_item))
				getResponse().setStatus(Status.SUCCESS_CREATED);
			else
				getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
		} else {
			getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
		}
	}

	@Override
	public Representation getRepresentation(Variant variant) {
		Representation representation = null;
		if (variant.getMediaType() == MediaType.TEXT_XML) {
			representation = this.getItems();
		} else {
			// do something
		}
		return representation;
	}
}